const fetch = require('node-fetch');
var crypto = require('crypto');
require('./logger');
const Msdb = require('./db/Msdb');
const { usequery, } = require('./routes/adminroute/shipSRM/server_util.js')

const appKey = 'mes_20231218'
const appSecret = 'ba5f88c9048d4681b91772f9a615605c'

const encrypt = function (message) {
    const hash = crypto.createHash('md5');
    hash.update(message);
    hash.end()
    const hexString = hash.read().toString('hex');
    return hexString;
};

async function fetchsync_util(url, type, param, rttype) {
    return new Promise(function (resolve, _reject) {
        fetch(url, {
            method: type,
            mode: 'cors',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(param)
        }).then(response => {
            return rttype == "json" ? response.json() : response.text();
        }).then(data => {
            resolve(data)
        });
    })
}
/**
 * 
 * @param {*} commandId  工艺参数id
 * @param {*} workOrderJson 工单JSON对象
 */
const api_gd_to_gylx = async (commandId, workOrderJson) => {
    return new Promise(async (resolve, _reject) => {
        let timestamp = new Date().getTime().toString();
        let sign = encrypt(`${appSecret}appKey=${appKey}&commandId=${commandId}&timestamp=${timestamp}&workOrderJson=${workOrderJson}${appSecret}`);
        let url = 'http://172.16.10.10:8099/openapi/technique/command/modify'
        let param = {
            "appKey": 'mes_20231218',
            "timestamp": timestamp,
            "commandId": commandId,
            "workOrderJson": workOrderJson,
            "sign": sign
        }
        console.log("请求的参数", param);
        let result = await fetchsync_util(url, 'POST', param, "json")
        console.log(result)
        resolve(result);
    })
}
/**
 * @param {Date} startTime 开始时间 2024-01-12 00:00:00
 * @param {Date} endTime 结束时间 2024-01-13 00:00:00
 * @param {String} deviceCode 设备编码
 * @param {Array} variableNameList 变量名称列表*/
const getDeviceHistoryParameterByCondition = async (startTime,endTime,deviceCode,variableNameList) => {
    return new Promise(async (resolve, _reject) => {
        var db=new Msdb();
        let url = 'http://116.148.228.248:8091/idev/open-api/getDeviceHistoryParameterByCondition.action'
        let param = {
           "deviceCode":deviceCode,
            "variableNameList":variableNameList,
            "startTime":startTime,
            "endTime":endTime,
            "secretKey":"ngPHA2oLmtE="
        }
        console.log("请求的参数", param);
        let result = await fetchsync_util(url, 'POST', param, "json")
        let resultData = result.rows
        console.log(resultData,"请求的结果");
        let dataList=[]
        for(let i=0;i<resultData[variableNameList[0]].length;i++){
            let data={}
            for(let j=0;j<variableNameList.length;j++){
                  data[variableNameList[j]] = resultData[variableNameList[j]][i].value
            }
            data.time=resultData[variableNameList[0]][i].time
            data.xh=i+1
            dataList.push(data)
        }
        resolve(dataList);
    })
}

/**
 * @param {String} deviceCode 设备编码
 * @param {Array} variableNameList 变量名称列表*/
const getDeviceRealParameterByCondition = async (deviceCode,variableNameList) => {
    return new Promise(async (resolve, _reject) => {
        var db=new Msdb();
        let url = 'http://116.148.228.248:8091/idev/open-api/getDeviceRealParameterByCondition.action'
        let param = {
            "deviceCodeList":[deviceCode],
            "variableNameList":variableNameList,
            "secretKey":"ngPHA2oLmtE="
        }
        let result = await fetchsync_util(url, 'POST', param, "json")
        let resultData = result.rows[deviceCode]
        let dataList=[]
        let data={}
        for(let i=0;i<resultData.length;i++){
            data[resultData[i].variableName] = resultData[i]
        }
        dataList.push(data)
        resolve(dataList);
    })
}

const getSqlStringai = async (startTime, endTime, deviceCode, variableNameList, listStr, sqlString, result) => {
    return new Promise(async (resolve, reject) => {
        const db = new Msdb();
        const url = 'http://116.148.228.248:8091/idev/open-api/getDeviceHistoryParameterByCondition.action';
        const param = {
            "deviceCode":deviceCode,
            "variableNameList":variableNameList,
            "startTime":startTime,
            "endTime":endTime,
            "secretKey":"ngPHA2oLmtE="
        };

        try {
            const response = await fetchsync_util(url, 'POST', param, "json");
            const resultData = response.rows;
            let rtdata = []
            for (let i = 0; i < resultData[variableNameList[0]].length; i++) {
                let data = {}
                for (let j = 0; j < variableNameList.length; j++) {
                    data[variableNameList[j]] = resultData[variableNameList[j]][i].value
                }
                data.time = resultData[variableNameList[0]][i].time
                data.xh = i + 1
                rtdata.push(data)
            }
            const dataList = rtdata.map(rt => {
                return listStr.map(field => ({
                    ...field,
                    value: rt[field.key]
                }));
            });

            let sqlList = '';
            dataList.forEach(dataRow => {
                const zdbmValues = dataRow
                    .filter(item => item.zdbm)
                    .map(item => item.zdbm)
                    .join(',');

                const valueValues = dataRow
                    .filter(item => item.zdbm)
                    .map(item => `'${item.value}'`)
                    .join(',');

                sqlList += `${sqlString} (id,${zdbmValues},create_time,update_time,sbbm,sbmc,sbxtbm) values (next value for seq_id,${valueValues},'${dataRow[1].value}','${dataRow[1].value}','${result.sbbm}','${result.sbmc}','${result.xybm}')\n`;
            });

            await db.update(sqlList);
            resolve('同步成功');
        } catch (error) {
            reject(error);
        }
    });
};
//同步设备数据
const getSyndevicedata = async () => {
    return new Promise(async (_resolve, _reject) => {
        var result = await usequery(`select sbbm,id,sbmc,xybm from shipSRM_sbda`)
        var dateTime = new Date();
        var year = dateTime.getFullYear();
        var month = String(dateTime.getMonth() + 1).padStart(2, '0');
        var day = String(dateTime.getDate()).padStart(2, '0');
        var hours = String(dateTime.getHours()).padStart(2, '0');
        var minutes = String(dateTime.getMinutes()).padStart(2, '0');
        var seconds = String(dateTime.getSeconds()).padStart(2, '0');
        var endDataStr = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
        dateTime.setTime(dateTime.getTime() - 60 * 1000);
        year = dateTime.getFullYear();
        month = String(dateTime.getMonth() + 1).padStart(2, '0');
        day = String(dateTime.getDate()).padStart(2, '0');
        hours = String(dateTime.getHours()).padStart(2, '0');
        minutes = String(dateTime.getMinutes()).padStart(2, '0');
        seconds = String(dateTime.getSeconds()).padStart(2, '0');
        var startDataStr = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
        var deviceCode =[]
        var variableNameList =[]
        var listStr =[]
        var sqlString =[]
        for (let i = 0; i < result.length; i++) {
            deviceCode.push(result[i].sbbm)
            const lastbm = result[i].sbbm.slice(-2)
            console.log(lastbm,"090---")
            if(lastbm==="07"){
                var tbZd = await usequery(`select zdmc, zdbm from shipSRM_oltable_mx where mainid ='1100158939'`)
                sqlString.push(`insert into shipSRM_sbtb_ghj`) 
            } else if (lastbm==="11" || lastbm==="12" || lastbm==="13"){
                var tbZd = await usequery(`select zdmc, zdbm from shipSRM_oltable_mx where mainid ='1100158944'`)
                sqlString.push(`insert into shipSRM_sbtb_dbj`)
            } else {
                var tbZd = await usequery(`select zdmc, zdbm from shipSRM_oltable_mx where mainid ='1100158934'`)
                sqlString.push(`insert into shipSRM_sbtb_gsj`)
            }
            
            var resultMx = await usequery(`select * from shipSRM_sbda_mx where mainid='${result[i].id}'`)
            variableNameList.push(resultMx.map(item => item.csbh)) 
            let variableNameListStr = resultMx.map((item, _index) => { return { show: true, key: item.csbh, title: item.csmc } })
            variableNameListStr.unshift({ show: true, key: "time", title: "时间" })
            variableNameListStr.unshift({ show: true, key: "xh", title: "序号" })
            // 创建一个以 zdmc 为键的映射对象
            const fieldMap = tbZd.reduce((acc, field) => {
                acc[field.zdmc] = field.zdbm;
                return acc;
            }, {});

            // 遍历 values 数组，将对应的 zdbm 添加到每个对象中
            listStr.push(variableNameListStr.map(value => ({
                ...value,
                zdbm: fieldMap[value.title] || ''
            }))) 
        }
        for (let i = 0; i < deviceCode.length; i++) {
            getSqlStringai(startDataStr, endDataStr, deviceCode[i], variableNameList[i],listStr[i],sqlString[i],result[i])
        }
    })
}
module.exports = {
     api_gd_to_gylx,
     getDeviceHistoryParameterByCondition,
     getDeviceRealParameterByCondition,
     getSyndevicedata
};